<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
 
/**
 * NGMenu Model
 */
class NGMenuModelNGMenu extends JModelAdmin
{
	protected $strCSS = array();
	protected $layCSS = null;

	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'NGMenu', $prefix = 'NGMenuTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true) 
	{
		// Get the form.
		$form = $this->loadForm('com_ngmenu.ngmenu', 'ngmenu', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) 
		{
			return false;
		}
		
		return $form;
	}
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData() 
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_ngmenu.edit.ngmenu.data', array());
		if (empty($data)) 
		{
			$data = $this->getItem();
		}

		return $data;
	}
	
	public function getItem($pk = null)
	{
		$menu = parent::getItem($pk);
		
		return $menu;
	}
	
	public function save($data)
	{
		$this->setUpdateFlag($data);
		
		$return = parent::save($data);
		
		$isNew = $this->getState('ngmenu.new');
		if ($isNew) {
			$this->updateNGItems();
		}
		$this->saveModule();
		
		$this->createFallbackMenu($data);

		return $return;
	}

	protected function createFallbackMenu($data)
	{
		require_once JPATH_COMPONENT.'/helpers/ngmenu.php';

		$ngmenu_id = $this->getState('ngmenu.id');
		
		$this->initStructureFile($data, $ngmenu_id);
		$this->initLayoutFile($data, $ngmenu_id);

		$this->createCssFile();
		
	}
	
	protected function initStructureFile($data, $ngmenu_id)
	{
		$selector = '#ng'.$ngmenu_id;
		$this->strCSS['file'] = NGMOD_PATH.DS.'mod_ngmenu'.DS.'str'.$ngmenu_id.'.css';
		
		$this->strCSS['common'][] = '/*Resetting of some element attributes*/';
		$this->strCSS['common'][] = 'div#ngmenu'.$ngmenu_id.'  table, div#ngmenu'.$ngmenu_id.'  td, div#ngmenu'.$ngmenu_id.'  tr{border:none;border-collapse:separate;}';
		$this->strCSS['common'][] = ' ';
		$this->strCSS['common'][] = 'ul'.$selector.',ul'.$selector.' ul{list-style:none;z-index:10000;}';
		$this->strCSS['common'][] = 'ul'.$selector.'{display:block;font-size:0;float:left;}';
		if ($data['is_horizontal']) {
			$this->strCSS['common'][] = 'ul'.$selector.' ul{display:none;position:absolute;left:0;top:100%;}';
			$this->strCSS['common'][] = 'ul'.$selector.' li{display:block;font-size:0;float:left;}';
		}else{
			$this->strCSS['common'][] = 'ul'.$selector.' ul{display:none;position:absolute;left:100%;top:0;}';
			$this->strCSS['common'][] = 'ul'.$selector.' li{display:block;font-size:0;}';
		}
		$this->strCSS['common'][] = 'ul'.$selector.' li:hover>*{display:block;}';
		$this->strCSS['common'][] = 'ul'.$selector.' li:hover{position:relative;}';
		$this->strCSS['common'][] = 'ul'.$selector.' ul ul{position:absolute;left:100%;top:0;}';
		$this->strCSS['common'][] = 'ul'.$selector.' table{border-collapse:collapse;}';
		$this->strCSS['common'][] = 'ul'.$selector.' a:active, ul'.$selector.' a:focus{outline-style:none;}';
		$this->strCSS['common'][] = 'ul'.$selector.' a{display:block;vertical-align:middle;cursor:pointer;}';
		$this->strCSS['common'][] = 'ul'.$selector.' ul li{float:none;}';
		$this->strCSS['common'][] = 'ul'.$selector.' li:hover>a{position:relative;}';
		$this->strCSS['common'][] = 'ul'.$selector.' li>a:hover{position:static !important;}';
		
		$this->strCSS['separator'][] = 'ul'.$selector.' li.sep{line-height:0;text-align:left;}';
		$this->strCSS['separator'][] = 'ul'.$selector.' li.sep *{float:none;display:inline-block;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' img{border:none;vertical-align:middle;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' img.over{display:none;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' li:hover > a img.def{display:none;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' li:hover > a img.over{display:inline;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' a:hover img.over,ul'.$selector.' a:hover ul img.def,ul'.$selector.' a:hover a:hover ul img.def,ul'.$selector.' a:hover a:hover img.over,ul'.$selector.' a:hover a:hover a:hover img.over{display:inline;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' a:hover img.def,ul'.$selector.' a:hover ul img.over,ul'.$selector.' a:hover a:hover ul img.over,ul'.$selector.' a:hover a:hover img.def,ul'.$selector.' a:hover a:hover a:hover img.def{display:none;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' a:hover ul,ul'.$selector.' a:hover a:hover ul{display:block;}';
		$this->strCSS['icon'][] = 'ul'.$selector.' a:hover ul ul{display:none;}';
		$this->strCSS['arrow'][] = 'ul'.$selector.' span{display:block;overflow:visible;background-position:right center;background-repeat:no-repeat;padding-right:14px;}';
		$this->strCSS['arrow'][] = 'ul'.$selector.' ul span,ul'.$selector.' a:hover table span{padding-right:14px;}';
		
	}
	
	protected function initLayoutFile($data, $ngmenu_id)
	{
		$selector = '#ng'.$ngmenu_id;
		$this->layCSS['file'] = NGMOD_PATH.DS.'mod_ngmenu'.DS.'lay'.$ngmenu_id.'.css';

		$menu_bg_color = 'background-color:'.$data['menu_back_color'].';';
		$menu_bg_img_repeat = 'background-repeat:'.$data['menu_back_image_repeat'].';';
		$menu_bg_img = ($data['menu_back_image_create']) ? 'background-image:url("'.JURI::root(true).$data['menu_back_image'].'");'.$menu_bg_img_repeat : '';
		$menu_border = 'border-width:'.$data['menu_border_width'].'px;border-style:'.$data['menu_border_style'].';border-color:'.$data['menu_border_color'].';';
		$item_spacing_ulul = ($data['item_spacing']) ? '0 '.$data['item_spacing'].'px '.$data['item_spacing'].'px;' : '0;';
		$sub_shadow = ($data['effect_shadow_create']) ? '-moz-box-shadow:2.1px 2.1px 3px '.$data['effect_shadow_color'].';-webkit-box-shadow:2.1px 2.1px 3px '.$data['effect_shadow_color'].';box-shadow:2.1px 2.1px 3px '.$data['effect_shadow_color'].';' : '';
		$no_wrap = ($data['no_wrap']) ? 'nowrap;' : 'normal;';
		$opacity_ms = ($data['effect_transparency_create']) ? '-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity='.$data['effect_transparency'].')";' : '';
		$op = $data['effect_transparency'] / 100;
		$opacity_rest = ($data['effect_transparency_create']) ? 'opacity:'.$op.';' : '';
//		$item_font_settings = 'text-align:'.$data['item_align_main'].';text-decoration:'.$data['font_decoration_normal'].';font:'.$data['font_weight'].' '.$data['font_size'].$data['font_size_unit'].' '.$data['font_family'].';color:'.$data['font_color_normal'].';';
		$item_font_settings = 'text-align:'.$data['item_align_main'].';text-decoration:'.$data['font_decoration_normal'].';font:'.NGMenuHelper::prepareFontWeight($data['font_weight'], true).' '.$data['font_size'].$data['font_size_unit'].' '.NGMenuHelper::prepareFontFamily($data['font_family']).';color:'.$data['font_color_normal'].';';
		$item_padding = 'padding:'.$data['item_padding_top'].'px '.$data['item_padding_right'].'px '.$data['item_padding_bottom'].'px '.$data['item_padding_left'].'px;';
		$item_bg_color = 'background-color:'.$data['item_back_color_normal'].';';
		$item_bg_image = ($data['item_back_image_create']) ? 'background-image:url("'.JURI::root(true).$data['item_back_image_normal'].'");background-repeat:repeat;' : '';
		$item_border = 'border-style:'.$data['item_border_style_normal'].';border-width:'.$data['item_border_width'].'px;border-color:'.$data['item_border_color_normal'].';';
//		$item_font_settings_over = 'font:'.$data['font_weight'].' '.$data['font_size'].$data['font_size_unit'].' '.$data['font_family'].';color:'.$data['font_color_over'].';text-decoration:'.$data['font_decoration_over'].';';
		$item_font_settings_over = 'font:'.NGMenuHelper::prepareFontWeight($data['font_weight'], true).' '.$data['font_size'].$data['font_size_unit'].' '.NGMenuHelper::prepareFontFamily($data['font_family']).';color:'.$data['font_color_over'].';text-decoration:'.$data['font_decoration_over'].';';
		$item_bg_color_over = 'background-color:'.$data['item_back_color_over'].';';
		$item_bg_image_over = ($data['item_back_image_create']) ? 'background-image:url("'.JURI::root(true).$data['item_back_image_over'].'");' : '';
		$item_border_over = 'border-style:'.$data['item_border_style_over'].';border-color:'.$data['item_border_color_over'].';';
		$main_arrow = ($data['main_arrow_image_create']) ? 'background-image:url("'.JURI::root(true).$data['main_arrow_image_normal'].'");' : '';
		$main_arrow_over = ($data['main_arrow_image_create']) ? 'background-image:url("'.JURI::root(true).$data['main_arrow_image_over'].'");' : '';
		$sub_arrow = ($data['sub_arrow_image_create']) ? 'background-image:url("'.JURI::root(true).$data['sub_arrow_image_normal'].'");' : '';
		$sub_arrow_over = ($data['sub_arrow_image_create']) ? 'background-image:url("'.JURI::root(true).$data['sub_arrow_image_over'].'");' : '';
		$main_separator_padding = 'padding-top:'.$data['separator_padding_top'].'px;padding-right:'.$data['separator_padding_right'].'px;padding-bottom:'.$data['separator_padding_bottom'].'px;padding-left:'.$data['separator_padding_left'].'px;';
		$main_separator_width = 'width:'.$data['separator_vwidth'].'px;';
		$main_separator_height = 'height:'.$data['separator_vheight'].$data['separator_vheight_unit'].';';
		$item_spacing_ulul = ($data['item_spacing']) ? 'padding:0 '.$data['item_spacing'].'px '.$data['item_spacing'].'px;' : 'padding:0;';
		
		if ($data['is_horizontal']) {
			$menu_width = 'width:auto;';
			$item_spacing_ul = ($data['item_spacing']) ? 'padding:'.$data['item_spacing'].'px '.$data['item_spacing'].'px '.$data['item_spacing'].'px '.$data['item_spacing'].'px;' : 'padding:0;';
			$item_spacing_ulliulli = ($data['item_spacing']) ? 'margin: 0 0 0 '.$data['item_spacing'].'px;' : 'margin:0;';
			$item_spacing_ululli = ($data['item_spacing']) ? 'margin:'.$data['item_spacing'].'px 0 0;' : 'margin:0;';
		}else{
			$menu_width = 'width:'.$data['menu_width'].$data['menu_width_unit'].';';
			$item_spacing_ul = ($data['item_spacing']) ? 'padding:0 '.$data['item_spacing'].'px '.$data['item_spacing'].'px;' : 'padding:0;';
			$item_spacing_ulliulli = ($data['item_spacing']) ? 'margin:'.$data['item_spacing'].'px 0 0;' : 'margin:0;';
			$item_spacing_ululli = '';
		}
		$this->layCSS['common'][] = 'ul'.$selector.'{'.$item_spacing_ul.$menu_width.'}';
		$this->layCSS['common'][] = 'ul'.$selector.'>li,ul'.$selector.' li{'.$item_spacing_ulliulli.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' ul>li{'.$item_spacing_ululli.'}';
		$this->layCSS['common'][] = 'ul'.$selector.',ul'.$selector.' ul{margin:0px;'.$menu_bg_color.$menu_bg_img.$menu_border.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' ul{'.$opacity_rest.$opacity_ms.$item_spacing_ulul.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' ul ul{'.$opacity_rest.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' li{white-space:'.$no_wrap.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' a{'.$item_font_settings.$item_padding.$item_bg_color.$item_bg_image.$item_border.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' ul a{text-align:'.$data['item_align_main'].';}';
		$this->layCSS['common'][] = 'ul'.$selector.' li:hover>a{'.$item_font_settings_over.$item_bg_color_over.$item_bg_image_over.$item_border_over.'}';
		$this->layCSS['common'][] = 'ul'.$selector.' li.active>a{'.$item_font_settings_over.$item_bg_color_over.$item_bg_image_over.$item_border_over.'}';

		$this->layCSS['icon'][] = 'ul'.$selector.' img{margin-right:3px;width:'.$data['main_image_width'].'px;height:'.$data['main_image_height'].'px;}';
		$this->layCSS['icon'][] = 'ul'.$selector.' ul img{width:'.$data['main_image_width'].'px;height:'.$data['main_image_height'].'px;}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' span{'.$main_arrow.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' li:hover>a>span{'.$main_arrow_over.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' a:hover span{'.$main_arrow_over.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' ul span,ul'.$selector.' a:hover table span{'.$sub_arrow.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' ul li:hover > a span{'.$sub_arrow_over.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' a:hover span,ul'.$selector.' a:hover a:hover span{'.$sub_arrow_over.'}';
		$this->layCSS['arrow'][] = 'ul'.$selector.' table span,ul'.$selector.' a:hover table span{'.$sub_arrow.'}';
		if ($data['main_separator_create']) {
			$this->layCSS['separator'][] = 'ul'.$selector.' li.sep{'.$main_separator_padding.$main_separator_width.$main_separator_height.'}';
			$this->layCSS['separator'][] = 'ul'.$selector.' li.sep *{padding-right:0;'.$main_separator_width.$main_separator_height.'}';
		}
		
	}
	
	protected function createCssFile(){
		$path = NGCOM_PATH;
		
		// write the structure file
		if (file_exists($this->strCSS['file'])) {
			$writable = is_writable($this->strCSS['file']);
		} else {
			$writable = is_writable($path);
		}
		
		$output = '';
		foreach ($this->strCSS as $section){
			if(is_array($section)){
				foreach ($section as $style){
					$output .= $style."\n";
				}
			}
		}
		
		if ($writable && ($fp = fopen($this->strCSS['file'], "w"))) {
			fputs($fp, $output, strlen($output));
			fclose($fp);
		}

		// write the layout file
		if (file_exists($this->layCSS['file'])) {
			$writable = is_writable($this->layCSS['file']);
		} else {
			$writable = is_writable($path);
		}
		
		$output = '';
		foreach ($this->layCSS as $section){
			if(is_array($section)){
				foreach ($section as $style){
					$output .= $style."\n";
				}
			}
		}
		
		if ($writable && ($fp = fopen($this->layCSS['file'], "w"))) {
			fputs($fp, $output, strlen($output));
			fclose($fp);
		}
	}

	protected function updateNGItems(){
		$ngmenu_id = $this->getState('ngmenu.id');
		$db =& JFactory::getDBO();
		
		$query = $db->getQuery(true);
		$query->update('#__ngmenu_item');
		$query->set("ngmenu_id = '".$ngmenu_id."'");
		$query->where("ngmenu_id = '0'");
		$db->setQuery($query);
		$db->query();
	}
	
	protected function setUpdateFlag(&$data){
		$data['update_config'] = '1';
	}
	
	protected function saveModule(){
	
		$ngmenu_id = $this->getState('ngmenu.id');
		
		$db =& JFactory::getDBO();
		
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from('#__ngmenu');
		$query->where("id='".$ngmenu_id."'");
		$db->setQuery($query);
		$menu = $db->loadObject();
		
		
		$query = $db->getQuery(true);
		$query->select('*');
		$query->from('#__modules');
		$query->where("id='".$menu->module_id."'");
		$db->setQuery($query);
		$row = $db->loadObject();
		
		$update_menu = false;
		if(!$row->id){
			$source = null;
//			if($copy_module){
//				$db->setQuery( "SELECT * FROM #__modules WHERE id='$copy_module'" );
//				$source = $db->loadObject();
//			}
			$module['id'] = 0;
			$module['title'] = 'NGM_'.$menu->name.'_'.$menu->template;
			$module['content'] = '';
			$module['ordering'] = 99;
			$module['position'] = ($source) ? $source->position : 'left';
			$module['published'] = 0;
			$module['module'] = 'mod_ngmenu';
			$module['access'] = ($source) ? $source->access : 1;
			$module['showtitle'] = ($source) ? $source->showtitle : 0;
			if($source){
				$set_params = array();
				$params = explode("\n", $source->params);
				foreach ($params as $idx => $param){
					$param = explode("=", $param);
					switch ($param[0]) {
						case 'menutype':
							$param[1] = $menu->name;
						break;
						case 'template':
							$param[1] = $menu->template;
						break;
					}
					$param = implode("=", $param);
					$set_params[] = $param;
				}
			}else{
				$set_params = array('moduleclass_sfx=ngm', 'menutype='.$menu->name, 'template='.$menu->template);
			}
			$module['params'] = implode("\n", $set_params);
			$update_menu = true;
		}else{
			$module['id'] = $row->id;
			$module['title'] = $row->title;
			$set_params = array();
			$params = explode("\n", $row->params);
			foreach ($params as $idx => $param){
				$param = explode("=", $param);
				switch ($param[0]) {
					case 'menutype':
						$param[1] = $menu->name;
					break;
					case 'template':
						$param[1] = $menu->template;
					break;
				}
				$param = implode("=", $param);
				$set_params[] = $param;
			}
			$module['params'] = implode("\n", $set_params);
		}

		$row =& JTable::getInstance('module');
		if (!$row->bind($module)) {
			return JError::raiseWarning( 500, $row->getError() );
		}

		if (!$row->check()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
	
		if (!$row->store()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
	
		$module_id = $row->id;
		$menu_id = $menu->id;

		if($update_menu){
			$db->setQuery( "UPDATE #__ngmenu SET module_id='$module_id' WHERE id='$menu_id'" );
			if (!$db->query()) {
				return JError::raiseWarning( 500, $db->getError() );
			}
		}
	
		$db->setQuery( "SELECT * FROM #__modules_menu WHERE moduleid='$module_id'" );
		$row = $db->loadObject();

		if(!$row->moduleid){
			$db->setQuery( "INSERT INTO #__modules_menu SET moduleid='$module_id', menuid='0'" );
			if (!$db->query()) {
				return JError::raiseWarning( 500, $db->getError() );
			}
		}
	
		return true;
	}
	
}
